#coding=utf-8
import re, logging, datetime
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext import db

from model import Email
from counter import Counter, CounterStatus
from google.appengine.api.labs import taskqueue

class GetMail(webapp.RequestHandler):
  def get(self):
    q = db.GqlQuery('SELECT * FROM Email where is_sended = False')
    emails = q.fetch(10)
    db.delete(emails)
    for email in emails:
      #email.is_sended = True
      #email.put()
      #logging.info(email.is_sended)
      self.response.out.write('%s<br/>'%email.addr)
    
      
class Importer(webapp.RequestHandler):
  def post(self):
    addrs = self.request.get('emails').split('\n')
    for a in addrs:
      email = Email(addr=a)
      email.save()
      
    self.response.out.write('ok')
    
class Deleter(webapp.RequestHandler):
  def get(self):
    model = self.request.get('model')
    c = Counter(model)
      
    q = db.GqlQuery('select * from %s where is_sended = True'%model)
    results = q.fetch(100)
    n = len(results)
    db.delete(results)
    c.change_count(n)
    
    if n == 100:
      taskqueue.add(url='/delete', method='GET', params={'model': model})
            
application = webapp.WSGIApplication([
  ('/import', Importer),
  ('/delete', Deleter),
  ('/counter', CounterStatus),
  
  ('/get_email', GetMail),
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
